﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Interop;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.IO;
using System.Globalization;
using System.Threading;
using System.Diagnostics;
using System.Windows.Threading;

namespace Subtitles
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        List<Line> subs1 = new List<Line>(), played = new List<Line>();
        Stopwatch watch = new Stopwatch();
        float offset;

        public MainWindow()
        {
            InitializeComponent();
            this.Topmost = true;
            Activate();
        }

        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
                this.DragMove();
            else if (e.ChangedButton == MouseButton.Right)
            {
                OpenFile();
            }
        }

        private void OpenFile()
        {
            OpenFileDialog d = new OpenFileDialog();
            watch.Stop();
            if (d.ShowDialog().Value)
            {

                StreamReader reader = new StreamReader(d.FileName);
                string[] lines = reader.ReadToEnd().Split(new[] { "\r\n\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                try
                {
                    subs1 = lines.Select(l => l.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries))
                        .Select(s => new Line()
                        {
                            number = Int32.Parse(s[0]),
                            time = s[1].Split(new[] { " --> " }, StringSplitOptions.RemoveEmptyEntries).Select(t => DateTime.ParseExact(t, "hh:mm:ss,fff", CultureInfo.InvariantCulture).TimeOfDay).ToArray(),
                            title = s[2] + (s.Count() > 3 ? "\r\n" + s[3] : "")
                        })
                        .ToList();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Cannot open file", MessageBoxButton.OK);
                    return;
                }

                watch = new Stopwatch();
                watch.Start();
                offset = 0;
                played = new List<Line>();
                DispatcherTimer timer = new DispatcherTimer();
                timer.Tick += delegate
                {
                    if (subs1.Count <= 0)
                    {
                        timer.Stop();
                        return;
                    }
                    timeLabel.Content = watch.Elapsed.Add(TimeSpan.FromSeconds(offset)).ToString(@"hh\:mm\:ss") + " " + subs1.Count + " " + played.Count + " " + subs1[0].time[0];
                    if (subs1[0].time[0] < watch.Elapsed.Add(TimeSpan.FromSeconds(offset)))
                    {
                        subsLabel.Content = subs1[0].title;
                    }
                    if (subs1[0].time[1] < watch.Elapsed.Add(TimeSpan.FromSeconds(offset)))
                    {
                        subsLabel.Content = "";
                        played.Insert(0, subs1[0]);
                        subs1.RemoveAt(0);

                    }
                };
                timer.Interval = TimeSpan.FromMilliseconds(200);
                timer.Start();
            }
        }

        private void Window_MouseEnter(object sender, MouseEventArgs e)
        {
            Brush br = Background;
            br.Opacity = 0.5;
            timeLabel.Visibility = System.Windows.Visibility.Visible;
        }

        private void Window_MouseLeave(object sender, MouseEventArgs e)
        {

            Brush br = Background;
            br.Opacity = 0;
            timeLabel.Visibility = System.Windows.Visibility.Hidden;
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Right)
            {
                offset += e.IsRepeat ? 3 : 0 + 0.5f;

                bool isRunning = watch.IsRunning;
                watch.Stop();
                while (subs1[0].time[1] < watch.Elapsed.Add(TimeSpan.FromSeconds(offset)))
                {
                    played.Insert(0, subs1[0]);
                    subs1.RemoveAt(0);
                }
                if (isRunning) watch.Start();
            }
            else if (e.Key == Key.Left)
            {
                offset -= e.IsRepeat ? 3 : 0 + 0.5f;

                bool isRunning = watch.IsRunning;
                watch.Stop();
                while (played.Count > 0 && played[0].time[0] > watch.Elapsed.Add(TimeSpan.FromSeconds(offset)))
                {
                    subsLabel.Content = played[0].title;
                    subs1.Insert(0, played[0]);
                    played.RemoveAt(0);
                }
                if (isRunning) watch.Start();
            }
            else if (e.Key == Key.X)
            {
                offset += e.IsRepeat ? 20 : 0 + 10f;

                bool isRunning = watch.IsRunning;
                watch.Stop();
                while (subs1[0].time[1] < watch.Elapsed.Add(TimeSpan.FromSeconds(offset)))
                {
                    played.Insert(0, subs1[0]);
                    subs1.RemoveAt(0);
                }
                if (isRunning) watch.Start();
            }
            else if (e.Key == Key.Z)
            {
                offset -= e.IsRepeat ? 20 : 0 + 10f;

                bool isRunning = watch.IsRunning;
                watch.Stop();
                while (played.Count > 0 && played[0].time[0] > watch.Elapsed.Add(TimeSpan.FromSeconds(offset)))
                {
                    subsLabel.Content = played[0].title;
                    subs1.Insert(0, played[0]);
                    played.RemoveAt(0);
                }
                if (isRunning) watch.Start();
            }
            else if (e.Key == Key.Escape)
            {
                if (
                    MessageBox.Show("Are you sure you want to close subtitles?", "Close subtitles",
                        MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    this.Close();
            }
            else if (e.Key == Key.Up)
                subsLabel.FontSize++;
            else if (e.Key == Key.Down)
                subsLabel.FontSize--;
            else if (e.Key == Key.Space)
                if (watch.IsRunning) watch.Stop();
                else watch.Start();
            else if (e.Key == Key.O)
                OpenFile();
            else if (e.Key == Key.F)
            {
                Brush br = Background;
                if (br.Opacity == 0)
                {
                    br.Opacity = 0.5;
                    timeLabel.Visibility = System.Windows.Visibility.Visible;
                }
                else
                {
                    br.Opacity = 0;
                    timeLabel.Visibility = System.Windows.Visibility.Hidden;
                }
            }

        }
    }

    class Line
    {
        public int number { get; set; }
        public string title { get; set; }
        public TimeSpan[] time { get; set; }
    }
}
